<template>
  <div class="workflow-list">
    <!-- 顶部操作栏 -->
    <div class="header">
      <div class="left">
        <h2>工作流管理</h2>
        <el-input
          v-model="searchKey"
          placeholder="搜索工作流"
          prefix-icon="Search"
          clearable
          @input="handleSearch"
          class="search-input"
        />
      </div>
      <div class="right">
        <el-button-group>
          <el-button 
            type="primary" 
            icon="Plus"
            @click="createWorkflow"
          >
            新建工作流
          </el-button>
          <el-button 
            :icon="isGridView ? 'List' : 'Grid'"
            @click="toggleView"
          />
        </el-button-group>
      </div>
    </div>

    <!-- 分类过滤 -->
    <div class="filters">
      <el-radio-group v-model="currentCategory" @change="handleCategoryChange">
        <el-radio-button label="">全部</el-radio-button>
        <el-radio-button 
          v-for="category in TEMPLATE_CATEGORIES"
          :key="category.code"
          :label="category.code"
        >
          <el-icon><component :is="category.icon" /></el-icon>
          {{ category.name }}
        </el-radio-button>
      </el-radio-group>
    </div>

    <!-- 网格视图 -->
    <div v-if="isGridView" class="grid-view">
      <el-card
        v-for="workflow in filteredWorkflows"
        :key="workflow.id"
        class="workflow-card"
        :body-style="{ padding: '0px' }"
      >
        <div class="card-preview">
          <el-image 
            :src="workflow.preview_image || '/placeholder.png'"
            fit="cover"
          />
          <div class="card-category">
            {{ getCategoryName(workflow.category) }}
          </div>
        </div>
        <div class="card-content">
          <h3>{{ workflow.name }}</h3>
          <p class="description">{{ workflow.description }}</p>
          <div class="card-footer">
            <span class="time">{{ formatDate(workflow.created_at) }}</span>
            <div class="actions">
              <el-button-group>
                <el-button 
                  size="small" 
                  @click="editWorkflow(workflow)"
                  icon="Edit"
                />
                <el-button 
                  size="small"
                  type="primary"
                  @click="executeWorkflow(workflow)"
                  icon="VideoPlay"
                />
                <el-button 
                  size="small"
                  type="danger"
                  @click="deleteWorkflow(workflow)"
                  icon="Delete"
                />
              </el-button-group>
            </div>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 列表视图 -->
    <el-table 
      v-else
      :data="filteredWorkflows" 
      v-loading="loading"
      class="list-view"
    >
      <el-table-column width="60">
        <template #default="{ row }">
          <el-avatar 
            :size="40"
            :src="row.preview_image || '/placeholder.png'"
          />
        </template>
      </el-table-column>
      <el-table-column prop="name" label="名称" min-width="200">
        <template #default="{ row }">
          <div class="name-cell">
            <span class="name">{{ row.name }}</span>
            <el-tag size="small" :type="getCategoryType(row.category)">
              {{ getCategoryName(row.category) }}
            </el-tag>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="description" label="描述" show-overflow-tooltip />
      <el-table-column prop="created_at" label="创建时间" width="180">
        <template #default="{ row }">
          {{ formatDate(row.created_at) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200" fixed="right">
        <template #default="{ row }">
          <el-button-group>
            <el-tooltip content="编辑">
              <el-button 
                size="small" 
                @click="editWorkflow(row)"
                icon="Edit"
              />
            </el-tooltip>
            <el-tooltip content="执行">
              <el-button 
                size="small"
                type="primary"
                @click="executeWorkflow(row)"
                icon="VideoPlay"
              />
            </el-tooltip>
            <el-tooltip content="删除">
              <el-button 
                size="small"
                type="danger"
                @click="deleteWorkflow(row)"
                icon="Delete"
              />
            </el-tooltip>
          </el-button-group>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :total="total"
        :page-sizes="[12, 24, 36, 48]"
        layout="total, sizes, prev, pager, next"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useWorkflowStore } from '@/stores/workflow'
import { TEMPLATE_CATEGORIES } from '@/config/template'
import { formatDate } from '@/utils/format'
import { useDebounceFn } from '@vueuse/core'

const router = useRouter()
const workflowStore = useWorkflowStore()
const workflows = ref([])
const loading = ref(false)

// 获取工作流列表
const getWorkflows = async () => {
  loading.value = true
  try {
    workflows.value = await workflowStore.getWorkflows()
  } catch (error) {
    ElMessage.error('获取工作流列表失败')
  }
  loading.value = false
}

// 获取分类名称
const getCategoryName = (code: string) => {
  return TEMPLATE_CATEGORIES.find(c => c.code === code)?.name || code
}

// 新建工作流
const createWorkflow = () => {
  router.push('/workflow/create')
}

// 编辑工作流
const editWorkflow = (workflow: any) => {
  router.push(`/workflow/edit/${workflow.id}`)
}

// 执行工作流
const executeWorkflow = (workflow: any) => {
  router.push(`/workflow/execute/${workflow.id}`)
}

// 删除工作流
const deleteWorkflow = async (workflow: any) => {
  try {
    await ElMessageBox.confirm('确定要删除该工作流吗?')
    await workflowStore.deleteWorkflow(workflow.id)
    ElMessage.success('删除成功')
    getWorkflows()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

// 视图切换
const isGridView = ref(true)
const toggleView = () => {
  isGridView.value = !isGridView.value
}

// 搜索和过滤
const searchKey = ref('')
const currentCategory = ref('')
const currentPage = ref(1)
const pageSize = ref(12)
const total = ref(0)

const filteredWorkflows = computed(() => {
  let result = workflows.value

  // 分类过滤
  if (currentCategory.value) {
    result = result.filter(w => w.category === currentCategory.value)
  }

  // 关键词搜索
  if (searchKey.value) {
    const key = searchKey.value.toLowerCase()
    result = result.filter(w => 
      w.name.toLowerCase().includes(key) || 
      w.description.toLowerCase().includes(key)
    )
  }

  total.value = result.length
  
  // 分页
  const start = (currentPage.value - 1) * pageSize.value
  return result.slice(start, start + pageSize.value)
})

// 获取分类样式
const getCategoryType = (category: string) => {
  const types = {
    'text2img': '',
    'img2img': 'success',
    'text2video': 'warning',
    'img2video': 'info'
  }
  return types[category] || ''
}

// 分页处理
const handleSizeChange = (val: number) => {
  pageSize.value = val
  currentPage.value = 1
}

const handleCurrentChange = (val: number) => {
  currentPage.value = val
}

// 搜索处理
const handleSearch = useDebounceFn(() => {
  currentPage.value = 1
}, 300)

// 分类切换
const handleCategoryChange = () => {
  currentPage.value = 1
}

onMounted(() => {
  getWorkflows()
})
</script>

<style scoped>
.workflow-list {
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header .left {
  display: flex;
  align-items: center;
  gap: 20px;
}

.search-input {
  width: 300px;
}

.filters {
  margin-bottom: 20px;
}

/* 网格视图样式 */
.grid-view {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 20px;
  margin-bottom: 20px;
}

.workflow-card {
  transition: transform 0.2s;
}

.workflow-card:hover {
  transform: translateY(-5px);
}

.card-preview {
  position: relative;
  height: 200px;
}

.card-preview .el-image {
  width: 100%;
  height: 100%;
}

.card-category {
  position: absolute;
  top: 10px;
  right: 10px;
  padding: 4px 8px;
  background: rgba(0, 0, 0, 0.6);
  color: white;
  border-radius: 4px;
}

.card-content {
  padding: 14px;
}

.card-content h3 {
  margin: 0 0 10px;
}

.description {
  color: #666;
  margin: 0 0 10px;
  height: 40px;
  overflow: hidden;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}

.card-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.time {
  color: #999;
  font-size: 13px;
}

/* 列表视图样式 */
.list-view {
  margin-bottom: 20px;
}

.name-cell {
  display: flex;
  align-items: center;
  gap: 10px;
}

.name {
  font-weight: 500;
}

/* 分页样式 */
.pagination {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}
</style> 